/*将url参数回填绑定给对应table 比如 SearcheTable*/
function setTableByUrl(table) {
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strArr = new Array();
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            var name = strs[i].split("=")[0];
            var val = strs[i].split("=")[1];
            strArr[i] = "\"" + name + "\":\"" + UrlDecode(val) + "\"";
        }
        var strJson = strArr.join(",");
        strJson = "{\"" + table.toUpperCase() + "\":[{" + strJson + "}]}";
        var datasource = eval("(" + strJson + ")");
        FormBind(datasource);
        return strJson;
    }
}

/*---UrlDecode-------*/
function UrlDecode(zipStr) {
    var uzipStr = "";
    for (var i = 0; i < zipStr.length; i++) {
        var chr = zipStr.charAt(i);
        if (chr == "+") {
            uzipStr += " ";
        } else if (chr == "%") {
            var asc = zipStr.substring(i + 1, i + 3);
            if (parseInt("0x" + asc) > 0x7f) {
                uzipStr += decodeURI("%" + asc.toString() + zipStr.substring(i + 3, i + 9).toString());
                i += 8;
            } else {
                uzipStr += AsciiToString(parseInt("0x" + asc));
                i += 2;
            }
        } else {
            uzipStr += chr;
        }
    }

    return uzipStr;
}

function StringToAscii(str) {
    return str.charCodeAt(0).toString(16);
}
function AsciiToString(asccode) {
    return String.fromCharCode(asccode);
}
function search(gridId, url) {
    var data = customFormToData("SearchTable");
    $("#" + gridId).jqGrid('setGridParam', {
        url: url, postData: JSON.parse(data), page: 1
    }).trigger("reloadGrid");
}

function rowDetail(url, cellvalue) {
    cellvalue = cellvalue == null ? "" : cellvalue;
    cellvalue = $.trim(cellvalue);
    return "<a href=\"#detail\" onclick=\"location.href='" + url + "'\">" + cellvalue + "</a>";
}

function openTab(url, title) {
    index = layer.open({
        title: title,
        area: [$(window).width() * 0.8 + 'px', $(window).height() * 0.8 + 'px'],
        offset: '100px',
        type: 2,
        scrollbar: false,
        content: url
    });
}

function openInspStatus() {
    layer.open({
        type: 2,
        title: false,
        shadeClose: true,
        area: ['880px', '50%'],
        content: $basePath + '/status/init?declNo=' + $("#declNo").val() + '&statusProcess=' + $("#declareInspStatusHidden").val()
    });
}

var index = "";


function getConsigneeCodeI(consigneeCodeI) {
    var aaaa = $("#" + consigneeCodeI).tautocomplete({
        relateKey: consigneeCodeI,
        placeholder: "请输入关键字",
        width: "800px",
        isCheck: false,
        regex: "^[a-zA-Z0-9\\s]+$",
        columns: ['收货人编号', '收货人名称', '收货人英文名称'],
        ajax: {
            url: $basePath + "/cache/getConsigneeCodeI", dataType: "json", type: "post", data: function () {
                return {
                    featureClass: "P", style: "full", maxRows: 11, name_startsWith: aaaa.searchdata()
                };
            }, success: function (jsonData) {
                var filterData = [];
                $.each(jsonData, function (i, item) {
                    var obj = {
                        id: item.CONSIGNEE_CODE_I + _split + item.CONSIGNEE_CNAME_I + _split + item.CONSIGNEE_ENAME_I,
                        CONSIGNEE_CODE_I: item.CONSIGNEE_CODE_I,
                        CONSIGNEE_CNAME_I: item.CONSIGNEE_CNAME_I,
                        CONSIGNEE_ENAME_I: item.CONSIGNEE_ENAME_I
                    };
                    filterData.push(obj);
                });
                return filterData;
            }
        },
        onchange: function () {
            var datas = aaaa.id().split(_split);
            var code_t = datas[0] || '';
            var cName = datas[1] || '';
            var eName = datas[2] || '';
            $("#" + consigneeCodeI).val(code_t);
            $("#consigneeCnameI").val(cName);
            $("#consigneeEnameI").val(eName);
            return;
        },
        setUserDefined: function () {
            $("#" + consigneeCodeI).val($("#" + consigneeCodeI + "_input").val());
        }
    });
}

/**
 * @param param
 *        {
 *        "id":'hsCodeZ',
 *        "decType":'2',
 *        "columns":['商品编码', '商品名称'],
 *        "width":'400px',
 *        "onchange":function(el, key, value){
 *
 *                   }
 *        }
 */
function getHsCode(param) {
    var elementId = param["id"];
    var decType = param["decType"];
    var columns = param["columns"] || ['商品编码','附加编码', '商品名称'];

    var width = param["width"] || $(window).width() * 0.4 + "px";
    var callback = param["onchange"];

    var selector = $("#" + elementId).tautocomplete({
        relateKey: elementId,
        placeholder: "请输入关键字",
        width: width,
        columns: columns,
        regex: "^[a-zA-Z0-9\\s]+$",
        ajax: {
            url: $basePath + "/cache/getHSCode",
            dataType: "json",
            type: "post",
            data: function () {
                return {
                    featureClass: "P",
                    style: "full",
                    maxRows: 11,
                    decType: decType,
                    name_startsWith: selector.searchdata()
                };
            }, success: function (jsonData) {
                var filterData = [];
                $.each(jsonData, function (i, item) {
                    var obj = {};
                    // 报关
                    if ('1' == decType) {
                        obj = {
                            id: JSON.stringify(item),
                            CODE_T: item.CODE_T,
                            CODE_S: item.CODE_S,
                            G_NAME: item.G_NAME
                        };
                    }
                    // 报检
                    if ('0' == decType) {
                        obj = {
                            id: JSON.stringify(item),
                            CODE_T: item.HS_CODE,
                            G_NAME: item.HS_CNAME
                        };
                    }

                    filterData.push(obj);
                });

                return filterData;
            }
        }, onchange: function () {

            var item = null;
            try {
                item = JSON.parse(selector.id());
            }
            catch (e) {
                item = {
                    "CODE_T": "",
                    "LEGALUNCN": "",
                    "CODE_S": "",
                    "INSP_MONITOR_COND": "",
                    "SECONDUNCN": "",
                    "SECONDUN": "",
                    "G_NAME": "",
                    "LEGALUN": ""
                };
            }

            if (typeof callback == 'function') {
                callback(selector, item);
                return;
            }

            if ("0" == decType) {
                $("#" + elementId).val(item.HS_CODE);
                $("input[name='" + param['goodsName'] + "']").val(item.HS_CNAME);
            }

            if ("1" == decType) {
                $("#" + elementId).val(item.CODE_T);
                $("#" + param['codeS'] + "").val(item.CODE_S);
                $("#" + param['goodsName'] + "").val(item.G_NAME);
            }

            return;
        }
    });
}

/**
 * 查询页面，必填的输入框校验和提示
 * @param arrayNames 属性名称
 * @returns {boolean} true or false
 */
function requiredQueryFields(arrayNames) {
    var $val;
    var titles = [];
    for (var name in arrayNames) {
        $val = $("[datafield='SearchTable." + arrayNames[name] + "']").val();
        if ($val) {
            return true;
        }

        titles.push($("[datafield='SearchTable." + arrayNames[name] + "']").closest("td").prev().text());
    }

    layer.alert(titles.toString() + "字段,请至少填写一个再进行查询！", {icon: 0, title: '提示信息', area: '450px'}, null);

    return false;
}

function getId(gridId) {
    var rowKey = $("#" + gridId + "").getGridParam("selrow");
    if (!rowKey) {
        ShowMessages("对不起,您没有选中任何记录", "系统提示", "msgwaring", null, 0);
        return [];
    } else {
        var selectedIDs = $("#" + gridId + "").getGridParam("selarrrow");
        var jsonArr = new Array();
        for (var i = 0; i < selectedIDs.length; i++) {
            jsonArr[i] = $("#" + gridId + "").jqGrid("getRowData", selectedIDs[i]);
        }
        return jsonArr;
    }
}

function popoverTip(params) {

    var setting = {
        animation: true, // boolean	true :apply a css fade transition to the tooltip
        html: true, // boolean	false :Insert html into the popover. If false, jquery's text method will be used to insert content into the dom. Use text if you're worried about XSS attacks.
        placement: "bottom", // string | function 'right' :how to position the popover - top | bottom | left | right
        selector: false, // string	false :if a selector is provided, tooltip objects will be delegated to the specified targets
        trigger: "click",// string	'click'	:how popover is triggered - click | hover | focus | manual
        title: "回执详情",// string | function '' :default title value if `title` attribute isn't present
        content: "",// string | function '' :default content value if `data-content` attribute isn't present
        delay: {show: 100, hide: 100},// number | object 0 :delay showing and hiding the popover (ms) - does not apply to manual trigger type If a number is supplied, delay is applied to both hide/show Object structure is: delay: { show: 500, hide: 100 }
        container: false// string | false :false Appends the popover to a specific element container: 'body'
    };

    $.extend(setting, params);

    $("#" + params.id).popover(setting);
}

function getStatusDetails(url, data) {
    var json;
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: data,
        async: false,
        success: function (data) {
            json = data;
        },
        error: function (msg) {

        }
    });

    return json;
}
/**
 * 初始化关回执信息页面
 * @param applicationIdZ 当前单据的唯一流水号
 * @param callback 回调函数，茹灿必须实现json对象的形式{}
 * @param errorCodes 针对可重复上传的错误编码数组
 */
function initStatusCPopover(applicationIdZ, resendUrl, errorCodes) {
    var statusList = getStatusDetails($basePath + "/status/getCustStatus", {"messageId": applicationIdZ});

    resendUrl += "?applicationIdZ=" + applicationIdZ + "&reDeclareType=C";
    popoverTip({id: "sendStatusC", content: initCustHtmlContent(statusList, resendUrl, errorCodes)});
}

/**
 * 将回执信息转化为html
 * @param statusList 当前单据的唯一流水号
 * @param callback 回调函数，茹灿必须实现json对象的形式{}
 * @param errorCodes 针对可重复上传的错误编码数组
 */
function initCustHtmlContent(statusList, resendUrl, errorCodes) {
    var html;
    var status, operateTd;
    html = "<table class='table table-hover table-bordered'><thead><tr><th>回执时间</th><th>回执详情</th><th>操作</th></tr></thead><tbody>";
    if (statusList && statusList.length > 0) {
        for (var i in statusList) {
            status = statusList[i];
            resendUrl += "&msgId=" + status.id;

            html += "<tr><td>" + status.inTime + "</td><td>" + status.msgCodeDisplay + "</td>";
            if (errorCodes[status.resultFlag]) {
                if (status.handleFlag == "0") {
                    operateTd = "<td><a class=\"btn-link\" href=\"" + resendUrl + "\"><span style='color:#00acec'>再次申报</span></a></td>";
                }
                if (status.handleFlag == "1") {
                    operateTd = "<td><a class=\"btn-link\" href=\"" + resendUrl + "&relateApplicationId=" + status.reDeclareAppId + "\"><span style='color:#00acec'>跟踪</span></a></td>";
                }
            } else {
                operateTd = "<td></td>";
            }


            html += operateTd + "<tr>";
        }
        html += "</tbody></table>";
    } else {
        html += "<tr><td colspan='3'>暂无详情信息</td></tr></tbody></table>"
    }
    return html;
}

function initInspHtmlContent(statusList, resendUrl, errorCodes) {
    var html;
    var status, operateTd;
    html = "<table class='table table-hover table-bordered'><thead><tr><th>回执时间</th><th>回执详情</th><th>操作</th></tr></thead><tbody>";
    if (statusList && statusList.length > 0) {
        var time;
        for (var i in statusList) {
            status = statusList[i];
            resendUrl += "&msgId=" + status.id;
            time = status.msgTime || status.messageTime;
            html += "<tr><td>" + time + "</td><td>" + status.msgCodeDisplay + "</td>";
            if (errorCodes[status.msgCode]) {
                if (status.handleFlag == "0") {
                    operateTd = "<td><a class=\"btn-link\" href=\"" + resendUrl + "\"><span style='color:#00acec'>再次申报</span></a></td>";
                }
                if (status.handleFlag == "1") {
                    operateTd = "<td><a class=\"btn-link\" href=\"" + resendUrl + "&relateApplicationId=" + status.reDeclareAppId + "\"><span style='color:#00acec'>跟踪</span></a></td>";
                }
            } else {
                operateTd = "<td></td>";
            }


            html += operateTd + "<tr>";
        }
        html += "</tbody></table>";
    } else {
        html += "<tr><td colspan='3'>暂无详情信息</td></tr></tbody></table>"
    }
    return html;
}

function initEntbackupStatusCPopover(applicationIdZ) {

    $.post($basePath + "/status/getEntbackupCustStatus", {"messageId": applicationIdZ}, function (html) {
        popoverTip({id: "sendStatusC", content: html});
    });
}

function initEntbackupStatusIPopover(applicationIdZ) {

    $.post($basePath + "/status/getEntbackupInspStatus", {"messageId": applicationIdZ}, function (html) {
        popoverTip({id: "sendStatusI", content: html});
    });
}

/**
 * 初始化检回执信息页面
 * @param applicationIdZ 当前单据的唯一流水号
 * @param callback 回调函数，茹灿必须实现json对象的形式{}
 * @param errorCodes 针对可重复上传的错误编码数组
 */
function initStatusIPopover(applicationIdZ, resendUrl, errorCodes) {
    var statusList = getStatusDetails($basePath + "/status/getInspStatus", {"messageId": applicationIdZ});
    resendUrl += "?applicationIdZ=" + applicationIdZ + "&reDeclareType=I";
    popoverTip({id: "sendStatusI", content: initInspHtmlContent(statusList, resendUrl, errorCodes)});
}

/**
 *
 * @param rowData
 * @param exclude
 * @returns {boolean}
 */
function checkDeleteRows(gridId, exclude) {
    var rowIds = $("#" + gridId).getGridParam("selarrrow");
    var len = rowIds.length;
    for (var i = 0; i < len; i++) {
        var row = $("#" + gridId).jqGrid("getRowData", rowIds[i]);
        if (!isExclude(row, exclude)) {
            ShowMessages("只允许删除本地暂存或申报失败的数据", "系统提示", "msgwaring", null, 0);
            return false;
        }
    }
    return true;
}

function isExclude(rowData, exclude) {
    var canDeleteC = false;
    var canDeleteI = false;

    for (var e in exclude) {
        if (rowData.sendStatusC == exclude[e]) {
            canDeleteC = true;
        }
    }

    for (var e in exclude) {
        if (rowData.sendStatusI == exclude[e]) {
            canDeleteI = true;
        }
    }

    return canDeleteI && canDeleteI;
}

function checkDeclareRows(selectedRowIds, exclude) {
    var len = selectedRowIds.length;
    for (var i = 0; i < len; i++) {
        var row = $("#corptable").jqGrid("getRowData", selectedRowIds[i]);
        if (!isExclude(row, exclude)) {
            ShowMessages("请选择未提交申请或申请失败的记录", "系统提示", "msgwaring", null, 0);
            return false;
        }
    }
    return true;
}
//将表单数据转为json
function form2Json(id) {
    var arr = $("#" + id).serializeArray();
    var jsonStr = "";
    var json = "";
    for (var i = 0; i < arr.length; i++) {
        if (isNotNull(arr[i].value)) {
            jsonStr += '"' + arr[i].name + '":"' + arr[i].value + '",'
        }
    }
    if (isNotNull(jsonStr)) {
        jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
        jsonStr = "{" + jsonStr + "}";
        json = JSON.parse(jsonStr);
    }
    return json;
}
function getColumn(tableId, column) {
    var ids = [];
    var rows = $('#' + tableId).datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i][column]);
    }
    return ids;
}


function popStatus(id, url, data) {
    $.post(url, data, function (html) {
        popoverTip({id: id, content: html, trigger: 'hover'});
    });
}
//公共方法判断是否为空
function isNull(param) {
    if ($.trim(param) == "" || param == null) {
        return true;
    } else {
        return false;
    }
}

function isNotNull(param) {
    if ($.trim(param) != "" && param != null) {
        return true;
    } else {
        return false;
    }
}

function array2Str(array) {
    var str = "";
    for (var i = 0; i < array.length; i++) {
        str += (array[i] + ",");
    }
    return str;
}
